package Filter::Utils;

use JIP::ToolSet; # load my commonly-used modules in a single import

use Exporter::Lite;
use cyrillic qw( detect convert );
use English qw( -no_match_vars );
use Encode qw( _utf8_on encode decode from_to );

our @EXPORT_OK = qw( getFileType nameDecoder pathDecoder );

sub nameDecoder {
    my $text = $ARG[0];

    if ( $text !~ /[^[:ascii:]]/ ) {
        _utf8_on( $text );

        return $text;
    }

    my $cp = detect( $text );

    if ( not $cp or $cp eq '28585' or $cp eq 'utf8' ) {
        _utf8_on( $text );

        return $text;
    }

    $text = convert( $cp, 1251, $text ) if $cp ne '1251';

    $text = encode( 'utf8', decode( 'cp1251', $text ) );

    from_to( $text, 'utf8', 'UTF-8' ); # strictify UTF

    _utf8_on( $text );

    return $text;
}

sub pathDecoder {
    return '/' if $ARG[0] eq '/';

    my @dirs = split m/\//, $ARG[0];

    shift @dirs;

    my $path;

    foreach ( @dirs ){ $path .= '/'. nameDecoder( $ARG ) }

    return $path;
}

sub getFileType {
    my $fileName = shift;

    my( $fileExtention ) = $fileName =~ m/([^\.]+)$/;

    given ( $fileExtention ) {
        when (/^(?:mp3|wav|ogg|flac|wma|m3u|ape|lqt|mmf|amr|mid|midi|wv)$/i) {
            return 'audio';
        }

        when (/^(?:avi|mov|vob|wmv|mpeg|mpg|asf|mkv|flv|mpg|m2v|ogm|mp4|divx|qt|vp6|rm)$/i) {
            return 'video';
        }

        when (/^(?:iso|vcd|nrg|img|cue|fcd|mds|mdf|ccd|cdi|pdi|bwt|bin)$/i) {
            return 'images';
        }

        when (/^(?:pdf|djv|djvu|doc|txt|html|shtml|xhtml|htm|chm|tex|mht|hlp|wrj|rtf|xml|ps|ppt|nfo)$/i) {
            return 'text';
        }

        when (/^(?:gif|jpeg|jpg|bmp|tiff|png|ico)$/i) {
            return 'pictures';
        }

        when (/^(?:gz|tgz|bz|bz2|zip|rar|arj|tar|czip|ace|cab|gzip|lzh|sqx|rs|uue|xxe|ucl|zlib|rpm|deb|7z|pak)$/i) {
            return 'archives';
        }

        when (/^(?:c|h|cpp|hpp|cc|hh|cs|java|jsp|js|py|pl|pm|asp|cgi|php|xsl|xslt|sql|tcl|rb)$/i) {
            return 'sources';
        }

        default { return 'other' }
    }
}

1;
